#include "LineDetect.h"

LineDetect::LineDetect(cv::Rect roi, int filterHalf, int filterThresshold)
{
    LineDetectSetup = new LineDetectInfo();
    LineDetectSetup->ROI = roi;
    LineDetectSetup->FilterHalf = filterHalf;
    LineDetectSetup->FilterThresshold = filterThresshold;

    this->IntensityLine = new int[LineDetectSetup->ROI.width];
}

LineInfo* LineDetect::DetectHorizontalLine(cv::Mat imageMat)
{
    cv::Mat detectImage = imageMat(LineDetectSetup->ROI);
    CalculateIntensityLine(detectImage, this->IntensityLine);
    return EdgeFilter(this->IntensityLine, LineDetectSetup->FilterHalf);
}

void LineDetect::CalculateIntensityLine(cv::Mat detectImage, int* intensityLine)
{
    for(int x=0; x<LineDetectSetup->ROI.width; x++)
    {
        intensityLine[x] = 0;
        for(int y=0; y<LineDetectSetup->ROI.height; y++)
        {
            cv::Scalar intensity = detectImage.at<uchar>(y, x);
            intensityLine[x] += intensity.val[0];
        }
    }
}

LineInfo* LineDetect::EdgeFilter(int* intensityLine, int filterHalf)
{
    int sumFirstHalf = LineDetect::FilterFirstHalf(intensityLine, filterHalf);
    int sumSecondHalf = LineDetect::FilterSecondHalf(intensityLine, filterHalf);
    
    int middle = filterHalf;
    int end = 2*filterHalf;

    int MaxFilterValue = sumFirstHalf-sumSecondHalf;
    int MaxFilterIndex = middle;
    
    for(int start=0; start<LineDetectSetup->ROI.width-2*filterHalf; start++)
    {
        sumFirstHalf = sumFirstHalf - intensityLine[start] + intensityLine[middle];
        sumSecondHalf = sumSecondHalf - intensityLine[middle] + intensityLine[end];
        middle++;
        end++;        
        
        int FilterValue = sumFirstHalf-sumSecondHalf;
        if(FilterValue > MaxFilterValue)
        {
            MaxFilterValue = FilterValue;
            MaxFilterIndex = middle;
        }        
    }
    
    if(MaxFilterValue > LineDetectSetup->FilterThresshold)
    {
        return new LineInfo(true, MaxFilterIndex);
    }
    return new LineInfo(false, 0);
}

int LineDetect::FilterFirstHalf(int* intensityLine, int filterHalf)
{
    int sumFirstHalf = 0;
    for(int x=0; x<filterHalf; x++)
    {
        sumFirstHalf += intensityLine[x];
    }
    return sumFirstHalf;
}

int LineDetect::FilterSecondHalf(int* intensityLine, int filterHalf)
{
    int sumSecondHalf = 0;
    for(int x=filterHalf; x<=2*filterHalf; x++)
    {
        sumSecondHalf += intensityLine[x];
    }    
    return sumSecondHalf;
}